﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace HelloWPF.Study.Windows
{
    /// <summary>
    /// 窗体IOC容器
    /// </summary>
    public class WindowContainer
    {
        private static Dictionary<string, WindowStruct> _regWindow = new Dictionary<string, WindowStruct>();

        /// <summary>
        /// 注册窗体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name">键名</param>
        /// <param name="owner"></param>
        public static void Register<T>(string name, System.Windows.Window owner = null)
        {
            if (!_regWindow.ContainsKey(name))
            {
                _regWindow.Add(name, new WindowStruct
                {
                    WindowType = typeof(T),
                    Owner = owner
                });
            }
        }

        /// <summary>
        /// 获取窗体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="dataContext"></param>
        /// <returns></returns>
        public static bool ShowDialog<T>(string name, T dataContext)
        {
            if (_regWindow.ContainsKey(name))
            {
                Type type = _regWindow[name].WindowType;
                //反射获取对象
                var window = (System.Windows.Window)Activator.CreateInstance(type);
                window.Owner = _regWindow[name].Owner;
                window.DataContext = dataContext;
                return window.ShowDialog() == true;
            }
            return false;
        }
    }

    public class WindowStruct
    {
        public Type WindowType { get; set; }
        public System.Windows.Window Owner { get; set; }
    }
}
